package com.xiaobo.client;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.xiaobo.util.HttpUtil;

public class ListNsrxxActivity extends Activity implements OnItemClickListener,
		OnClickListener {
	private int pageCount=5;// 每页显示数
	private int currentPage = 1;// 当前页
	private int totalNumber = 0;// 总数
	private String searchInfo;// 查询关键字
	private ArrayList<String> nsrxxList;// 纳税人信息
	private ListView listView;
	private Button previousButton;// 上一页
	private Button nextButton;// 下一页
	private TextView totalView;// 总数

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listnsrxx);
		// 获得mainActivity中传过来的纳税人名称
		System.out.println("123444455555666");
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		searchInfo = bundle.getString("nsrmc");
		System.out.println(searchInfo+"11111111111111");
		// 获得翻页按钮对象
		previousButton = (Button) findViewById(R.id.previousButton);
		nextButton = (Button) findViewById(R.id.nextButton);
		listView = (ListView) findViewById(R.id.searchResultList);
		totalView = (TextView) findViewById(R.id.totleNumber);
		// 设置监听
		previousButton.setOnClickListener(this);
		nextButton.setOnClickListener(this);
		listView.setOnItemClickListener(this);		
		// 总数信息
		totalNumber = getNsrxxTotal(searchInfo);
		System.out.println(totalNumber+"2222222222222");		
		totalView.setText("共计：" + totalNumber + "条");	
		//返回纳税人信息列表，json数组格式的字符串
		String nsrxxJson = getNsrxxList(searchInfo,currentPage,pageCount);
		sendMSG(nsrxxJson);
		//设置listview
		listView.setOnItemClickListener(ListNsrxxActivity.this);
		// 第一页，上一页按钮置灰
		previousButton.setEnabled(false);
		// 如果只有一页，下一页按钮置灰
		if ((currentPage * pageCount) >= totalNumber) {
			nextButton.setEnabled(false);
		}
	}
	//发送消息
	public void sendMSG(String nsrxxJson){
		if(nsrxxJson!=null){
			ArrayList<String> nsrxxList = new ArrayList<String>();
			try {
				//根据返回的JSON数组格式字符串，创建JSON数组
				JSONArray array = new JSONArray(nsrxxJson);
				for(int i=0;i<array.length();i++){
					JSONObject obj = array.getJSONObject(i);
					nsrxxList.add(obj.toString());
				}
				//totalNumber = nsrxxList.size();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Message msg = new Message();//创建消息
			Bundle data = new Bundle();//创建数据
			data.putStringArrayList("nsrxxList", nsrxxList);
			msg.what = 1;//设置消息的what值
			msg.setData(data);//存放数据
			handler.sendMessage(msg);
			
		}else{
			showDialog("纳税人不存在");
		}		
	}
	//显示信息
	public void showDialog(String msg){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg).setCancelable(false).setPositiveButton("确定", new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
			
		});
		AlertDialog alert = builder.create();
		alert.show();
		
	}
	//创建handle对象
	Handler handler = new Handler(){
		//用于接收Handler消息
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if(msg.what==1){
				// 获得数据
				Bundle data = msg.getData();
				nsrxxList = (ArrayList<String>)data.get("nsrxxList");
				//为ListView准备内容适配器
				MyBaseAdapter mba = new MyBaseAdapter(nsrxxList);
				listView.setAdapter(mba);
				mba.notifyDataSetChanged();
			}
		}
		
	};
	public class MyBaseAdapter extends BaseAdapter{
		private ArrayList<String> nsrxxList;
		//构造方法
		public MyBaseAdapter(ArrayList<String> nsrxxList){
			this.nsrxxList=nsrxxList;
		}
		//总共多少个选项
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return nsrxxList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		//动态生成每个下拉项对应的View
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			//初始化LinearLayout1
			LinearLayout linearLayout1 = new LinearLayout(ListNsrxxActivity.this);
			linearLayout1.setOrientation(LinearLayout.HORIZONTAL);//设置方向			
			try {
			//初始化ImageView
			ImageView img1 = new ImageView(ListNsrxxActivity.this);
			img1.setBackgroundResource(R.drawable.nsr);
			//设置图片显示方式
			img1.setScaleType(ImageView.ScaleType.FIT_XY);
			img1.setLayoutParams(new Gallery.LayoutParams(50,50));
			//添加到LinearLayout中
			linearLayout1.addView(img1);
			//初始化LinearLayout2
			LinearLayout linearLayout2 = new LinearLayout(ListNsrxxActivity.this);
			linearLayout2.setOrientation(LinearLayout.VERTICAL);//设置朝向
			//初始化TextView,美食名称
			TextView nsrbm =new TextView(ListNsrxxActivity.this);	
			JSONObject obj = new JSONObject(nsrxxList.get(position));
			nsrbm.setText("纳税人编码："+obj.getString("nsrbm"));
			//设置文字
			nsrbm.setTextSize(12);//设置字体大小
			nsrbm.setTextColor(Color.RED);
			nsrbm.setPadding(5,1,5,1);//设置四周留白
			nsrbm.setMaxLines(1);//设置行数
			nsrbm.setGravity(Gravity.CENTER);//对齐方式
		    linearLayout2.addView(nsrbm);//添加到LinearLayout中
		    
			//初始化TextView
			TextView nsrmc = new TextView(ListNsrxxActivity.this);

			nsrmc.setText(obj.getString("nsrmc"));

			nsrmc.setTextSize(14);//设置字体大小
			nsrmc.setTextColor(Color.GRAY);//文字的颜色
			nsrmc.setPadding(5,1,5,1);//设置四周留白
			nsrmc.setMaxLines(1);//设置行数
			nsrmc.setGravity(Gravity.CENTER);//对齐方式
		    linearLayout2.addView(nsrmc);//添加到LinearLayout中
		    //添加到linearLayout1
		    linearLayout1.addView(linearLayout2);
		    
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			return linearLayout1;
		}
		
	}
	//获得总数
	public int getNsrxxTotal(String nsrmc){
		int totalNum =0;
		String result=null;
		String url = HttpUtil.getNsrxxTotalURL;
		// 获得请求对象
		HttpPost req = HttpUtil.getHttpPost(url);
		// 设置表单参数
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("nsrmc",nsrmc));
		// 设置请求对象的编码
		try {
			req.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
			result = HttpUtil.getStringByPost(req);
			System.out.println(result+" 4444444444444444");
			JSONObject obj = new JSONObject(result);
			result = obj.getString("number");
			if(result!=null&&!result.equals("")){
				totalNum = Integer.parseInt(result);
				System.out.println(totalNum+" 55555555555555555");
				return totalNum;
			}			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//return null;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return 0;
	}
	public String getNsrxxList(String nsrmc,int currentPage,int pageCount){
		String result=null;
		String url = HttpUtil.getNsrxxListURL;
		// 获得请求对象
		HttpPost req = HttpUtil.getHttpPost(url);
		// 设置表单参数
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("nsrmc",nsrmc));
		params.add(new BasicNameValuePair("currentPage",String.valueOf(currentPage)));
		params.add(new BasicNameValuePair("pageCount",String.valueOf(pageCount)));
		// 设置请求对象的编码
		try {
			req.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
			result = HttpUtil.getStringByPost(req);
			return result;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}		
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		try {
			//获得被选中Item的纳税人信息
			JSONObject obj = new JSONObject(nsrxxList.get(arg2));
			Intent intent = new Intent(ListNsrxxActivity.this,NsrxxActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("nsrbm", obj.getString("nsrbm"));
			bundle.putString("nsrmc", obj.getString("nsrmc"));
			bundle.putString("nsrnbm", obj.getString("nsrnbm"));
			intent.putExtras(bundle);
			startActivity(intent);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v == previousButton){
			currentPage = currentPage-1;
			if(currentPage==1){
				previousButton.setEnabled(false);
			}
			if((currentPage*pageCount) < totalNumber){
				nextButton.setEnabled(true);
		    }
			String nsrxxJson = getNsrxxList(searchInfo,currentPage,pageCount);
			sendMSG(nsrxxJson);
		}else if(v==nextButton){
			currentPage = currentPage+1;
			if(currentPage!=1){
				previousButton.setEnabled(true);
			}
			if(currentPage*pageCount>=totalNumber){
				nextButton.setEnabled(false);
			}
			String nsrxxJson = getNsrxxList(searchInfo,currentPage,pageCount);
			sendMSG(nsrxxJson);			
		}

	}
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(ListNsrxxActivity.this,ExitSystemActivity.class);
		startActivity(intent);
		return false;
	}
}
